package com.ybkj.daijia.api.member.v3;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.server.Config;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 客户地区相关
 *
 * @author bo
 */
@Controller("areaV3Controller")
@RequestMapping(value = "member/api/rest/v3")
public class AreaController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private CompanyService companyService;

    /**
     * 获取地区列表
     *
     * @param appKey
     * @return
     */
    @RequestMapping("listAreas")
    public ModelAndView listAreas(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("area/viewlist");

        String content = listAreasFunc(acKey, companyId, longitude, latitude);

        mv.addObject("feeContent", HtmlHelper.htmlscripttext(content));
        return mv;

    }

    /**
     * 获取地区列表(过APP测评)
     *
     * @param appKey
     * @return
     */
    @RequestMapping("listAreas2")
    public @ResponseBody
    ResultTransport listAreas2(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude,
        HttpServletRequest request) {

        String content = listAreasFunc(acKey, companyId, longitude, latitude);

        try {
            String path = String.format("%s/WEB-INF/views/area/", Config.getWebapp());

            Configuration cfg = new Configuration();

            cfg.setTemplateLoader(new FileTemplateLoader(new File(path)));
            cfg.setDefaultEncoding("UTF-8");

            Template template = cfg.getTemplate("viewlist2.ftl");

            Map<String, Object> root = new HashMap<String, Object>();
            root.put("ctx", request.getContextPath());
            root.put("feeContent", HtmlHelper.htmlscripttext(content));

            StringWriter writer = new StringWriter();
            template.process(root, writer);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            Map<String, String> datamap = new HashMap<String, String>();
            datamap.put("content", HtmlHelper.replaceBlank(writer.toString()));
            instance.setData(datamap);
            return instance;

        } catch (IOException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        } catch (TemplateException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    private String listAreasFunc(String acKey, Long companyId,
        Double longitude, Double latitude) {

        Company company = null;
        if (StringUtils.isNotBlank(acKey)) {
            company = companyService.findByAppKey(acKey);
        } else if (longitude != null && latitude != null) {
            String city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
            List<Company> companyList = null;
            if (StringUtils.isNotBlank(city)) {
                companyList = companyService.findByAreaCityName(city);
            }
            if (!CollectionUtils.isEmpty(companyList)) {
                for (Company c : companyList) {
                    if (c.getId().equals(companyId)) {
                        company = c;
                        break;
                    }
                }

                List<Company> notMainCompanys = new ArrayList<Company>();
                Company cityMainCompany = null;

                if (null == company) {
                    for (Company c : companyList) {
                        if (!c.isCompanyType()) {
                            if (StringUtils.isBlank(c.getAppKey())) {
                                notMainCompanys.add(c);
                            }
                        } else {
                            cityMainCompany = c;
                        }
                    }
                    if (!CollectionUtils.isEmpty(notMainCompanys)) {
                        company = notMainCompanys.get(new Random().nextInt(notMainCompanys.size()));
                    }
                }

                if (null == company) {
                    if (null != cityMainCompany) {
                        company = cityMainCompany;
                    }
                }

            }
        }
        if (company == null) {
            company = companyService.getMain();
        }

        return company.getFeeContent();
    }

}
